<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <!-- web路径：
    不以/开始的相对路径，找资源，以当前资源的路径为基准，经常容易出问题。
    以/开始的相对路径，找资源，以服务器的路径为标准,需要加上项目名做前缀.
     -->
    <script type="text/javascript" src="${APP_PATH }/js/jquery.min.js"></script>
    <script type="text/javascript" src="${APP_PATH }/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="${APP_PATH }/css/bootstrap.min.css">

</head>
<body>
<!-- 员工修改的模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_static"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-4">
                            <label class="radio-inline">
                                <input type="radio" name="empGender" id="gender_update_input_nan" value="男" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="empGender" id="gender_update_input_nv" value="女"> 女
                            </label>
                        </div>
                        <label class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="empDept">
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" name="empEmail" class="form-control" id="email_update_input"
                                   placeholder="email@hncch.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">电话</label>
                        <div class="col-sm-10">
                            <input type="text" name="empPhone" class="form-control" id="phone_update_input"
                                   placeholder="12345678901">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>


<!-- 员工添加的模态框 -->
<div class="modal fade" id="empInsertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName_insert_input" placeholder="员工姓名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-4">
                            <label class="radio-inline">
                                <input type="radio" name="empGender" id="gender_insert_input_nan" value="男" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="empGender" id="gender_insert_input_nv" value="女"> 女
                            </label>
                        </div>
                        <label class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="empDept">
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" name="empEmail" class="form-control" id="email_insert_input"
                                   placeholder="email@hncch.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">电话</label>
                        <div class="col-sm-10">
                            <input type="text" name="empPhone" class="form-control" id="phone_insert_input"
                                   placeholder="12345678901">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_insert_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 员工删除的模态框（小） -->
<div class="modal fade" id="empDeleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工删除</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <span id="del_names" class="help-block" ></span>
                    <span id="del_ids" class="help-block"></span>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-danger" id="emp_delete_btn">删除</button>
            </div>
        </div>
    </div>
</div>


<!-- 搭建显示页面 -->
<div class="container">
    <!-- 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1>IUDS_BOOT</h1>
        </div>
    </div>
    <!-- 菜单 -->
    <div class="row">
        <div class="col-md-12">
            <ul class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#">员工</a></li>
                <li role="presentation"><a href="#">项目</a></li>
                <li role="presentation"><a href="#">备用</a></li>
                <li role="presentation"><a href="#">关于</a></li>


                <li role="presentation" id="alert_message"></li>
                <li class="pull-right" role="presentation"><a href="#">关于</a></li>
            </ul>

        </div>
    </div>
    <!-- 显示表格数据 -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover nav-tabs" id="emps_table">
                <thead>
                    <tr>
                        <th style="vertical-align: inherit;">
                            <input type="checkbox" id="check_all"/>
                        </th>
                        <th style="vertical-align: inherit;">ID</th>
                        <th style="vertical-align: inherit;">姓名</th>
                        <th style="vertical-align: inherit;">性别</th>
                        <th style="vertical-align: inherit;">邮箱</th>
                        <th style="vertical-align: inherit;">电话</th>
                        <th style="vertical-align: inherit;">部门</th>
                        <th style="vertical-align: inherit;">
                            <button class="btn btn-sm btn-primary" id="emp_insert_modal_btn">
                                <span class="glyphicon glyphicon-plus"></span>新增</button>
                            <button class="btn btn-sm btn-danger" id="emp_delete_modal_btn">
                                <span class="glyphicon glyphicon-remove"></span>删除</button>
                        </th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <!-- 显示分页信息 -->
    <div class="row">
        <!--分页文字信息  -->
        <div class="col-xs-6 col-sm-4" id="page_info_area">

        </div>
        <!-- 分页条信息 -->
        <div class="col-xs-6 col-sm-4" id="page_nav_area">

        </div>
    </div>

</div>
<script type="text/javascript">

    var totalPages, currentPage;
    //1、页面加载完成以后，直接去发送ajax请求,要到分页数据
    $(function () {
        //去首页
        to_page(1);
    });

    function to_page(pn) {
        $.ajax({
            url: "${APP_PATH}/emps",
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                show_alert_info(result.code, result.info);
                //1、解析并显示员工数据
                build_emps_table(result);
                //2、解析并显示分页信息
                build_page_info(result);
                //3、解析显示分页条数据
                build_page_nav(result);
            }
        });
    }

    function build_emps_table(result) {
        //清空table表格
        $("#emps_table tbody").empty();
        var emps = result.data.pageInfo.list;
        $.each(emps, function (index, item) {
            var td = $("<td></td>").css("vertical-align","inherit");
            var checkItemTd = td.clone().append("<input type='checkbox' class='check_item'/></td>");
            var idTd = td.clone().append(item.empId);
            var nameTd = td.clone().append(item.empName);
            var genderTd = td.clone().append(item.empGender);
            var emailTd = td.clone().append(item.empEmail);
            var phoneTd = td.clone().append(item.empPhone);
            var deptTd = td.clone().append(item.empDept);

            var updateBtn = $("<button></button>").addClass("btn btn-primary btn-sm update_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
            //为编辑按钮添加一个自定义的属性，来表示当前员工id
            updateBtn.attr("update-id", item.empId);
            var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            //为删除按钮添加一个自定义的属性来表示当前删除的员工id
            deleteBtn.attr("delete-id", item.empId);
            var btnTd = td.clone().append(updateBtn).append(" ").append(deleteBtn);

            //append方法执行完成以后还是返回原来的元素
            var tr = $("<tr></tr>");
            var emp = new Date(item.empDate);
            var now = new Date();
            if((now - emp)/1000 < 60){
                tr.addClass("alert-success")
            }
            tr.append(checkItemTd)
                .append(idTd)
                .append(nameTd)
                .append(genderTd)
                .append(emailTd)
                .append(phoneTd)
                .append(deptTd)
                .append(btnTd)
                .appendTo("#emps_table tbody");
        });
    }
    //解析显示分页信息
    function build_page_info(result) {
        $("#page_info_area").empty();
        var ul = $("<ul></ul>").addClass("pagination")
        var li = $("<li></li>").append($("<a></a>").append("当前第" +
            result.data.pageInfo.pageNum + "页")).addClass("disabled");
        li.append($("<a></a>").append("总共有" +
            result.data.pageInfo.pages + "页")).addClass("disabled");
        li.append($("<a></a>").append("共" +
            result.data.pageInfo.total + "条记录")).addClass("disabled");
        ul.append(li);
        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_info_area");

        totalPages = result.data.pageInfo.pages;
        currentPage = result.data.pageInfo.pageNum;
    }
    //解析显示分页条，点击分页要能去下一页....
    function build_page_nav(result) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");

        //构建元素
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if (result.data.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            //为元素添加点击翻页的事件
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(result.data.pageInfo.pageNum - 1);
            });
        }


        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
        if (result.data.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            nextPageLi.click(function () {
                to_page(result.data.pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                to_page(result.data.pageInfo.pages);
            });
        }


        //添加首页和前一页 的提示
        ul.append(firstPageLi).append(prePageLi);
        //1,2，3遍历给ul中添加页码提示
        $.each(result.data.pageInfo.navigatepageNums, function (index, item) {

            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if (result.data.pageInfo.pageNum == item) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                to_page(item);
            });
            ul.append(numLi);
        });
        //添加下一页和末页 的提示
        ul.append(nextPageLi).append(lastPageLi);

        //把ul加入到nav
        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }

    //清空表单样式及内容
    function reset_form(ele) {
        $(ele)[0].reset();
        //清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    //点击新增按钮弹出模态框。
    $("#emp_insert_modal_btn").click(function () {
        //清除表单数据（表单完整重置（表单的数据，表单的样式））
        reset_form("#empInsertModal form");
        //s$("")[0].reset();
        //发送ajax请求，查出部门信息，显示在下拉列表中
        getDepts("#empInsertModal select");
        //弹出模态框
        $("#empInsertModal").modal({
            backdrop: "static"
        });
    });

    //查出所有的部门信息并显示在下拉列表中
    function getDepts(ele) {
        //清空之前下拉列表的值
        $(ele).empty();
        var data = {"depts":[{"deptId":1,"deptName":"开发部"},{"deptId":2,"deptName":"测试部"},{"deptId":2,"deptName":"运维部"}]};
        $.each(data.depts, function () {
            var optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptName);
            optionEle.appendTo(ele);
        });
    }

    //校验表单数据
    function validate_insert_form() {
        //1、拿到要校验的数据，使用正则表达式
        var empName = $("#empName_insert_input").val();
        var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if (!regName.test(empName)) {
            //alert("用户名可以是2-5位中文或者6-16位英文和数字的组合");
            show_validate_msg("#empName_insert_input", "error", "用户名可以是2-5位中文或者6-16位英文和数字的组合");
            return false;
        } else {
            show_validate_msg("#empName_insert_input", "success", "");
        }
        ;

        //2、校验邮箱信息
        var email = $("#email_insert_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(email)) {
            //alert("邮箱格式不正确");
            show_validate_msg("#email_insert_input", "error", "邮箱格式不正确");
            return false;
        } else {
            show_validate_msg("#email_insert_input", "success", "");
        }

        //2、校验电话信息
        var phone = $("#phone_insert_input").val();
        var regPhone = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
        if (!regPhone.test(phone)) {
            //alert("电话号码不正确");
            show_validate_msg("#phone_insert_input", "error", "电话号码不正确");
            return false;
        } else {
            show_validate_msg("#phone_insert_input", "success", "");
        }
        return true;
    }
    //显示操作结果的提示信息
    function show_alert_info(status, msg) {
        //清除当前元素的校验状态
        $("#alert_message").empty();
        var div = $("<div></div>").addClass("alert");
        if (200 == status) {
            div.addClass("alert-success");
        } else if ("error" == status) {
            div.addClass("alert-danger");
        }
        div.addClass("alert-dismissible");
        div.append('<button type="button" class="close" data-dismiss="alert">&times;</button>');
        div.append(msg).css({"padding":"10px 40px 10px 40px","margin-bottom":"0px"});
        $("#alert_message").append(div);
        setTimeout(function () {
            $("#alert_message").empty();
        }, 7000);
    }

    //显示校验结果的提示信息
    function show_validate_msg(ele, status, msg) {
        //清除当前元素的校验状态
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if ("success" == status) {
            $(ele).parent().addClass("has-success");
        } else if ("error" == status) {
            $(ele).parent().addClass("has-error");
        }
        $(ele).next("span").text(msg);
    }

    //校验用户名是否可用
    $("#empName_insert_input").change(function () {
        //发送ajax请求校验用户名是否可用
        var empName = this.value;
        $.ajax({
            url: "${APP_PATH}/checkName",
            data: "empName=" + empName,
            type: "POST",
            success: function (result) {
                if (result.code == 200) {
                    show_validate_msg("#empName_insert_input", "success", "用户名可用");
                    $("#emp_insert_btn").attr("ajax-va", "success");
                } else {
                    show_validate_msg("#empName_insert_input", "error", result.data.va_msg);
                    $("#emp_insert_btn").attr("ajax-va", "error");
                }
            }
        });
    });

    //点击保存，保存员工。
    $("#emp_insert_btn").click(function () {
        //1、模态框中填写的表单数据提交给服务器进行保存
        //1、先对要提交给服务器的数据进行校验
        if (!validate_insert_form()) {
            return false;
        }
        ;
        //1、判断之前的ajax用户名校验是否成功。如果成功。
        if ($(this).attr("ajax-va") == "error") {
            return false;
        }

        //2、发送ajax请求保存员工
        $.ajax({
            url: "${APP_PATH}/emp",
            type: "POST",
            data: $("#empInsertModal form").serialize(),
            success: function (result) {
                if (result.code == 200) {
                    show_alert_info(result.code, result.info);
                    //员工保存成功；
                    //1、关闭模态框
                    $("#empInsertModal").modal('hide');

                    //2、来到最后一页，显示刚才保存的数据
                    //发送ajax请求显示最后一页数据即可
                    to_page(totalPages);
                } else {
                    //显示失败信息
                    //console.log(result);
                    //有哪个字段的错误信息就显示哪个字段的；
                    if (undefined != result.data.errorFields.email) {
                        //显示邮箱错误信息
                        show_validate_msg("#email_insert_input", "error", result.data.errorFields.empEmail);
                    }
                    if (undefined != result.data.errorFields.empName) {
                        //显示员工名字的错误信息
                        show_validate_msg("#empName_insert_input", "error", result.data.errorFields.empName);
                    }
                }
            }
        });
    });

    //1、我们是按钮创建之前就绑定了click，所以绑定不上。
    //1）、可以在创建按钮的时候绑定。    2）、绑定点击.live()
    //jquery新版没有live，使用on进行替代
    $(document).on("click", ".update_btn", function () {

        //1、查出部门信息，并显示部门列表
        getDepts("#empUpdateModal select");
        //2、查出员工信息，显示员工信息
        getEmp($(this).attr("update-id"));

        //3、把员工的id传递给模态框的更新按钮
        $("#emp_update_btn").attr("update-id", $(this).attr("update-id"));
        $("#empUpdateModal").modal({
            backdrop: "static"
        });
    });

    function getEmp(id) {
        $.ajax({
            url: "${APP_PATH}/emp/" + id,
            type: "GET",
            success: function (result) {
                var empData = result.data.emp;
                $("#empName_update_static").text(empData.empName);
                $("#empUpdateModal input[name=empGender]").val([empData.empGender]);
                $("#email_update_input").val(empData.empEmail);
                $("#phone_update_input").val(empData.empPhone);
                $("#empUpdateModal select").val([empData.empDept]);
            }
        });
    }

    //点击更新，更新员工信息
    $("#emp_update_btn").click(function () {
        //验证邮箱是否合法
        //1、校验邮箱信息
        var email = $("#email_update_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(email)) {
            show_validate_msg("#email_update_input", "error", "邮箱格式不正确");
            return false;
        } else {
            show_validate_msg("#email_update_input", "success", "");
        }

        //2、发送ajax请求保存更新的员工数据
        $.ajax({
            url: "${APP_PATH}/emp/" + $(this).attr("update-id"),
            type: "PUT",
            data: $("#empUpdateModal form").serialize(),
            success: function (result) {
                show_alert_info(result.code, result.info);
                //1、关闭对话框
                $("#empUpdateModal").modal("hide");
                //2、回到本页面
                to_page(currentPage);
            }
        });
    });

    //单个删除
    $(document).on("click", ".delete_btn", function () {
        //1、弹出是否确认删除对话框
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        var empId = $(this).attr("delete-id");
        //设置数据
        $("#del_names").text("确认删除【" + empName + "】吗？");
        $("#del_ids").attr("delete-id", empId);
        //弹出模态框
        $("#empDeleteModal").modal({
            backdrop: "static"
        });
    });

    //完成全选/全不选功能
    $("#check_all").click(function () {
        //attr获取checked是undefined;
        //我们这些dom原生的属性；attr获取自定义属性的值；
        //prop修改和读取dom原生属性的值
        $(".check_item").prop("checked", $(this).prop("checked"));
    });

    //check_item
    $(document).on("click", ".check_item", function () {
        //判断当前选择中的元素是否5个
        var flag = $(".check_item:checked").length == $(".check_item").length;
        $("#check_all").prop("checked", flag);
    });

    //点击全部删除，就批量删除
    $("#emp_delete_modal_btn").click(function () {
        //
        var empNames = "";
        var empIds = "";
        $.each($(".check_item:checked"), function () {
            //this
            empNames += $(this).parents("tr").find("td:eq(2)").text() + ",";
            //组装员工id字符串
            empIds += $(this).parents("tr").find("td:eq(1)").text() + "-";
        });
        //去除empNames多余的
        empNames = empNames.substring(0, empNames.length - 1);
        //去除删除的id多余的-
        empIds = empIds.substring(0, empIds.length - 1);

        //设置数据
        $("#del_names").text("确认删除【" + empNames + "】吗？");
        $("#del_ids").attr("delete-id", empIds);
        //弹出模态框
        $("#empDeleteModal").modal({
            backdrop: "static"
        });
    });

    //点击删除，删除员工。
    $("#emp_delete_btn").click(function () {
        //1、关闭模态框
        $("#empeleteModal").modal('hide');
        //2、发送ajax请求删除
        $.ajax({
            url: "${APP_PATH}/emp/" + $("#del_ids").attr("delete-id"),
            type: "DELETE",
            success: function (result) {
                show_alert_info(result.code, result.info);
                //回到当前页面
                to_page(currentPage);
            }
        });
    });
</script>
</body>
</html>